package com.dkd.http.controller;

import com.dkd.http.vo.LoginReq;
import com.dkd.http.vo.LoginResp;
import com.dkd.service.UserService;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 用户管理
 */
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
@Slf4j
public class UserController {
	private final UserService userService;
	private final DefaultKaptcha kaptcha;
	
	
	@Autowired
	private RedisTemplate<String, String> redisTemplate;
	
	
	/**
	 * 登录
	 * @param req
	 * @return
	 * @throws IOException
	 */
	@PostMapping("/login")
	public LoginResp login(@RequestBody LoginReq req) throws IOException {
		return userService.login(req);
	}
	
	/**
	 * 生成登录手机验证码
	 * @param mobile
	 */
	@GetMapping("/code/{mobile}")
	public void generateCode(@PathVariable String mobile) {
		userService.sendCode(mobile);
	}
	
	/**
	 * 获取图片验证码
	 * @param httpServletRequest
	 * @param httpServletResponse
	 */
	@GetMapping("/imageCode/{clientToken}")
	public void getImageCode(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, @PathVariable String clientToken) throws IOException {
		ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
		String createText = kaptcha.createText();//生成随机字母+数字(4位)
		BufferedImage challenge = kaptcha.createImage(createText);//根据文本构建图片
		ImageIO.write(challenge, "jpg", jpegOutputStream);
		byte[] captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
		httpServletResponse.setContentType("image/jpeg");
		ServletOutputStream responseOutputStream =
				httpServletResponse.getOutputStream();
		responseOutputStream.write(captchaChallengeAsJpeg);
		responseOutputStream.flush();
		responseOutputStream.close();
		//将验证码存入redis  2分钟超时
		redisTemplate.boundValueOps(clientToken).set(createText, 120, TimeUnit.SECONDS);
	}
}
